import axios from "axios";
import { message } from "ant-design-vue";
import { storage } from "@/utils/Storage";
import { ACCESS_TOKEN } from "@/store/mutation-types.js";
import { baseUrl, authUrlList } from '@/config/settings'
import { CODEENUM } from '@/config'
import Qs from 'qs'


// 请求超时时间
var request = axios.create({
  timeout: 3 * 60 * 1000,
  baseURL: baseUrl,
  withCredentials: true, //允许跨域携带cookie
  async: true,
  crossDomain: true,
});

// 请求拦截器
request.interceptors.request.use(config => {
  // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token
  const token = storage.get(ACCESS_TOKEN);
  if (authUrlList.includes(config.url) && !token) {
    message.error('无权访问，请登录后重试！');
    return
  }
  if (token) {
    config.headers["token"] = token;
  }
  if (config.headers['content-type'] != 'multipart/form-data') {
    config.data = Qs.stringify(config.data)
  }
  return config;
}, error => {
  // Message.error({message: '请求超时!'});
  return Promise.error(error);
});

//响应拦截
request.interceptors.response.use(res => {
  const result = res.data;
  if (res.config.message !== 'custom') {
    if (result.code === CODEENUM.GD_ERROR) {
      message.error(result.message || '数据获取失败');
    } else if (result.code === CODEENUM.OP_SUCCESS) {
      message.success(result.message || '操作成功');
    } else if (result.code === CODEENUM.OP_ERROR) {
      message.error(result.message);
    } else if (result.code === CODEENUM.AHTU_ERROR) {
      // message.error('权限不足无法访问');
    } else if (result.code === CODEENUM.TOKEN_ERROR) {
      message.error('无权访问，请登录后重试！');
    }

    if (result.code !== CODEENUM.GD_SUCCESS && result.code !== CODEENUM.OP_SUCCESS) {
      return Promise.reject(result.message);
    } else {
      return Promise.resolve(result);
    }
  } else {
    return Promise.resolve(result);
  }
}, err => {
  message.error('网络请求失败，请稍后再试');
  return Promise.reject(err);
});

export default request;

export { request as axios };
